package com.kun.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import redis.clients.jedis.Jedis;

import com.kun.dao.CityDao;
import com.kun.util.RedisUtil;

public class CityDataServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		String jsonStr = this.getCitiesFromRedis();
		PrintWriter printWriter = resp.getWriter();
		printWriter.print(jsonStr);
		printWriter.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}
	
	/**
	 * 从redis缓存中获取数据
	 * @return
	 */
	public String getCitiesFromRedis(){
		Jedis jedis = RedisUtil.getJedis();
		String cityjson="";
		if(jedis.exists("cities")){
			cityjson = jedis.get("cities");
			Long rpop = jedis.del("cities");
			System.out.println("********2****************"+rpop);
		} else {
			CityDao cityDao = new CityDao();
			System.out.println("********3****************");
			cityDao.pushCities();
			cityjson = jedis.get("cities");
			
		}
		return cityjson;
	}

}
